package com.cyx.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cyx.reggie.common.R;
import com.cyx.reggie.dto.DishDto;
import com.cyx.reggie.entity.Category;
import com.cyx.reggie.entity.Dish;
import com.cyx.reggie.entity.DishFlavor;
import com.cyx.reggie.service.CategoryService;
import com.cyx.reggie.service.DishFlavorService;
import com.cyx.reggie.service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author 陈彦西
 * @date 2024/7/15 下午2:42
 */
@RestController
@RequestMapping("/dish")
@Slf4j
public class DishController {
    @Autowired
    private DishService dishService;
    @Autowired
    private DishFlavorService dishFlavorService;
    @Autowired
    private CategoryService categoryService;

    /**
     * 新增菜品
     */
    @PostMapping("/save")
    public R<String> save(@RequestBody DishDto dishDto) {

        log.info(dishDto.toString());
        dishService.saveWithFlavor(dishDto);
        return R.success("新增菜品成功");
    }

    /**
     * 菜品信息分页查询
     *
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    public R<Page> page(int page, int pageSize, String name) {
        //构造分页构造器对象
        Page<Dish> pageInfo = new Page<>(page, pageSize);
        Page<DishDto> dishDtoPage = new Page<>();
        //条件构造器
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();

        //添加过滤条件
        queryWrapper.like(name != null, Dish::getName, name);
        //添加排序条件
        queryWrapper.orderByDesc(Dish::getUpdateTime);
        //执行分页查询
        dishService.page(pageInfo, queryWrapper);

        //对象拷贝
        BeanUtils.copyProperties(pageInfo, dishDtoPage, "records");
        List<Dish> records = pageInfo.getRecords();
        List<DishDto> list = records.stream().map((item) -> {
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(item, dishDto);
            Long categoryId = item.getCategoryId();
            //根据id查询分类对象
            Category category = categoryService.getById(categoryId);
            if (category != null) {
                String categoryName = category.getName();
                dishDto.setCategoryName(categoryName);
            }

            return dishDto;
        }).collect(Collectors.toList());

        dishDtoPage.setRecords(list);
        return R.success(dishDtoPage);
    }

    /**
     * 根据id查询菜品信息和对应的口味信息
     *
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public R<DishDto> get(@PathVariable Long id) {
        DishDto dishDto = dishService.getByIdWithFlavor(id);
        return R.success(dishDto);

    }

    /**
     * 修改菜品
     * 更新涉及两张表
     */
    @PutMapping
    public R<String> update(@RequestBody DishDto dishDto) {

        log.info(dishDto.toString());
        dishService.updateWithFlavor(dishDto);
        return R.success("更新菜品成功");
    }

    /**
     * 根据条件查询对应的菜品
     *
     * @param dish
     * @return
     */
//    @GetMapping("/list")
//    public R<List<Dish>> list(Dish dish){
//        //构造查询条件
//        LambdaQueryWrapper<Dish> queryWrapper=new LambdaQueryWrapper<>();
//        queryWrapper.eq(dish.getCategoryId()!=null,Dish::getCategoryId,dish.getCategoryId());
//       //添加条件，查询状态为1（起售状态）的菜品
//        queryWrapper.eq(Dish::getStatus,1);
//       //添加排序条件
//        queryWrapper.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);
//        List<Dish> list=dishService.list(queryWrapper);
//
//        return R.success(list);
//    }
    @GetMapping("/list")
    public R<List<DishDto>> list(Dish dish) {
        //构造查询条件
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(dish.getCategoryId() != null, Dish::getCategoryId, dish.getCategoryId());
        //添加条件，查询状态为1（起售状态）的菜品
        queryWrapper.eq(Dish::getStatus, 1);
        //添加排序条件
        queryWrapper.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);
        List<Dish> list = dishService.list(queryWrapper);

        List<DishDto> dishDtosList = list.stream().map((item) -> {
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(item, dishDto);
            Long categoryId = item.getCategoryId();
            //根据id查询分类对象
            Category category = categoryService.getById(categoryId);
            if (category != null) {
                String categoryName = category.getName();
                dishDto.setCategoryName(categoryName);
            }
            //以前菜品的id
            Long dishId = item.getId();
            LambdaQueryWrapper<DishFlavor> queryWrapper1 = new LambdaQueryWrapper<>();
            queryWrapper1.eq(DishFlavor::getId, dishId);
            //SQL:select * from dish_flavor where dish_id =?
            List<DishFlavor> list1 = dishFlavorService.list(queryWrapper1);
            dishDto.setFlavors(list1);
            return dishDto;

        }).collect(Collectors.toList());


        return R.success(dishDtosList);
    }


    /**
     * 删除和批量删除，调用的接口为一个，所有只需要写一次
     *
     * @param
     * @return
     */

    @DeleteMapping()
    public R<String> delete(String ids) {

        log.info(ids.toString());
        //  使用逗号分割字符串，并转换为List
        List<String> id = Arrays.asList(ids.split(","));
        dishService.removeByIds(id);
        return R.success("删除成功");
    }

    /**
     * 起售和停售,批量处理调用的接口为一个
     *
     * @param
     * @return
     */
    @PostMapping("/status/{type}")
    public R<String> updateStatus(@PathVariable Integer type, String ids) {
        String[] id = ids.split(",");
        if (type == 0) {
            // 禁售
            LambdaUpdateWrapper<Dish> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.in(Dish::getId, id);
            updateWrapper.set(Dish::getStatus, 0);
            dishService.update(updateWrapper);
        } else if (type == 1) {
            // 起售
            LambdaUpdateWrapper<Dish> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.in(Dish::getId, id);
            updateWrapper.set(Dish::getStatus, 1);
            dishService.update(updateWrapper);
        } else {
            return R.error("修改菜品状态失败");
        }

        return R.success("修改菜品状态成功");
    }
}
//    @PostMapping("/status/0")
//    public R<String> status(String ids) {
//        log.info(ids.toString());
//        List<String> idList = Arrays.asList(ids.split(","));
//        for (String oneId : idList) {
//            try {
//                Long id = Long.parseLong(oneId); // 将字符串转换为Long
////               Dish dish = new Dish();
////               dish.setId(id); // 这里设置单个ID
//                DishDto dishDto = dishService.getByIdWithFlavor(id); // 根据ID查询菜品对象
//
//                if (dishDto == null) {
//                    log.warn("未找到ID为 {} 的菜品，跳过状态更新。", id);
//                    continue; // 如果没有找到菜品，跳过当前循环的其余部分
//                }
//
//                Integer currentStatus = dishDto.getStatus(); // 获取当前状态
//                dishDto.setStatus(currentStatus == 1 ? 0 : 1); // 切换状态
//
//                dishService.updateById(dishDto); // 假设updateById接受Dish对象并更新其状态
//            } catch (NumberFormatException e) {
//                log.error("ID转换错误: {}", oneId, e);
//                // 处理转换异常，例如跳过当前ID或返回错误信息
//            }
//        }
//        return R.success("状态修改成功");
//    }
//}